import router  from '@/router'
import {post}  from '@/util/request'
import storage from '@/util/storage'
import iView                 from 'iview'

export default {
	namespace:'base',
	namespaced:true,
	state:{
		isLoading:false,
		size:{
			_num:1,
			height:document.documentElement.clientHeight
		},
		userinfo:storage.get("userinfo"),
		loginError:{
			username:'',
			password:''
		}
	},
	mutations:{
		changeSize(state,{height}){
			state.size = {height,_num:state.size._num+1};
		},
		changeUserinfo(state,userinfo){
			state.userinfo = userinfo;
		},
		changeLoginError(state,err){
			state.loginError = err;
		},
		changeLoading(state,isLoading){
			state.isLoading = isLoading;
		}
	},
	actions:{
		resize({commit}){
			commit('changeSize',{height:document.documentElement.clientHeight});
		},
		setUserinfo({commit},userinfo){
			storage.set("userinfo",userinfo);
			commit('changeUserinfo',userinfo);
		},
		initIndex({commit,dispatch}){

		},
		async login({commit,dispatch},{username,password,isJZpwd,returl}){
			let ue = '',pe = '';
			commit('changeLoading',true);
			commit('changeLoginError',{username:ue,password:pe});
			let res = await post('/doLogin',{username,password});
			commit('changeLoading',false);
			let data = res.data;
			if(data){
				if(data.sta === 200){
					storage.set("userinfo",data);
					commit('changeUserinfo',data);
					storage.set("isJZpwd",isJZpwd?'true':'false');
					if(isJZpwd){
						storage.set("uaname",username);
						storage.set("uapwd",password);
					}else{
						storage.set("uaname",'');
						storage.set("uapwd",'');
					}

					// 跳转
					let has = data.resources.find(r => r.url === returl);
					if (returl && has){
						router.push(returl);
					} else {
						let f = data.resources.find(r => r.url);
						router.push(f.url);
					}
				}else if(data.sta === 308){
					// ue = data.msg;
					iView.Message.error(data.msg);
				}else{
					ue = data.msg.indexOf("不存在")>-1?'账号不存在':''
					pe = data.msg.indexOf("不正确")>-1?'密码错误':''
				}
				commit('changeLoginError',{username:ue,password:pe});
			}
		},
		async logout({commit,dispatch}){
			let res = await post('/loginOut');
			commit('reset',{},{root:true});
			router.replace('/login');
		}
	}
}
